<!-- 质检申请 -->
<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" label-position="left">
      <!-- 填写质检申请 -->
      <template>
        <el-divider content-position="center">质检申请</el-divider>
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="质检类型" prop="type">
              <el-select :disabled="sqDisable" clearable style="width: 100%;" v-model="ruleForm.type" placeholder="请选择">
                <el-option v-for="item in dict.type.xmgl_task_qualitytype" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检申请日期" prop="promoteTime">
              <el-date-picker :disabled="sqDisable" clearable style="width: 100%;" v-model="ruleForm.promoteTime"
                type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-button :disabled="sqDisable" size='mini' style="margin-left: 15px;" type="primary" icon="el-icon-plus"
            @click="openContentModal">添加质检内容</el-button>
        </el-row>
        <!-- 表格 -->
        <el-table style="width: 100%; margin-top: 15px;" row-key="id" ref="table" :data="tableData">
          <el-table-column label="序号" type="index" align="center">
          </el-table-column>
          <el-table-column label="质检成果" align="center" prop="name" />
          <el-table-column label="质检成果内容" align="center" prop="content" />
          <el-table-column label="质检成果数量" align="center" prop="taskCount" />
          <el-table-column label="质检成果单位" align="center" prop="taskUnit" />
          <el-table-column label="成果存放目录" align="center" prop="storagePath">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button :disabled="sqDisable" size="mini" type="text" icon="el-icon-edit"
                @click="handleUpdate(scope.row)">修改</el-button>
              <el-button :disabled="sqDisable" size="mini" type="text" icon="el-icon-delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row style="margin-top: 15px;">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input :disabled="sqDisable" clearable style="width: 100%;" v-model="ruleForm.remark" placeholder="请输入"
                type="textarea" :rows="4">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

    <!-- 分发质检任务 -->
    <el-form v-if="ffShowPage" :model="ffForm" :rules="ffrules" ref="ffForm" label-width="110px" label-position="left">
      <template>
        <el-divider content-position="center">分发质检任务</el-divider>
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="质检方式" prop="checkMethod">
              <el-select :disabled="ffDisable" clearable style="width: 100%;" v-model="ffForm.checkMethod"
                placeholder="请选择">
                <el-option v-for="item in  dict.type.xmgl_task_qualitymethod" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检负责人" prop="responsiblePersonId">
              <el-select :disabled="ffDisable" ref="zjfzrSelect" filterable clearable style="width: 100%;"
                v-model="ffForm.responsiblePersonId" placeholder="请选择">
                <el-option v-for="item in fzrUserList" :key="item.value" :label="item.name" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="质检执行部门" prop="executeDeptId">
              <treeselect :disable-branch-nodes="true" :disabled="ffDisable" v-model="ffForm.executeDeptId"
                :options="deptTreeList" :normalizer="normalizer" placeholder="选择部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检执行人" prop="executorId">
              <el-select :disabled="ffDisable" filterable clearable style="width: 100%;" v-model="ffForm.executorId"
                placeholder="请选择">
                <el-option v-for="item in zxrUserList" :key="item.value" :label="item.name" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

    <!-- 质检检查 -->
    <el-form v-if="zjShowPage" :model="zjForm" :rules="zjrules" ref="zjForm" label-width="110px" label-position="left">
      <template>
        <el-divider content-position="center">质检检查</el-divider>
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="质检完成时间" prop="checkTime">
              <el-date-picker :disabled="zjDisable" clearable style="width: 100%;" v-model="zjForm.checkTime" type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检结论" prop="checkConclusion">
              <el-select :disabled="zjDisable" clearable style="width: 100%;" v-model="zjForm.checkConclusion"
                placeholder="请选择">
                <el-option value="3" label="质检通过">
                </el-option>
                <el-option value="4" label="质检不通过">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="主要质量问题" prop="mainQualityProblem">
              <el-input :disabled="zjDisable" clearable style="width: 100%;" v-model="zjForm.mainQualityProblem"
                placeholder="请输入" type="textarea" :rows="4">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

    <!-- 质检整改意见 -->
    <el-form v-if="yjShowPage" :model="yjForm" :rules="yjrules" ref="yjForm" label-width="110px" label-position="left">
      <template>
        <el-divider content-position="center">质检整改意见</el-divider>
        <el-row style="margin-top: 15px;">
          <el-col :span="24">
            <el-form-item label="生产部门负责人整改意见" prop="reformOpinions">
              <el-input :disabled="zgDisable" clearable style="width: 100%;" v-model="yjForm.reformOpinions"
                placeholder="请输入" type="textarea" :rows="4">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="填写人" prop="reformPromoterId">
              <el-select :disabled="zgDisable" filterable clearable style="width: 100%;" v-model="yjForm.reformPromoterId"
                placeholder="请选择">
                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="填写时间" prop="reformPromoteDate">
              <el-date-picker :disabled="zgDisable" clearable style="width: 100%;" v-model="yjForm.reformPromoteDate"
                type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

    <!-- 总工办审批 -->
    <el-form v-if="zgbShowPage" :model="zgbForm" :rules="zgbrules" ref="zgbForm" label-width="110px"
      label-position="left">
      <template>
        <el-divider content-position="center">总工办审批</el-divider>
        <el-row style="margin-top: 15px;">
          <el-col :span="24">
            <el-form-item label="总工办质量管理员审批意见" prop="approveOpinions">
              <el-input :disabled="zgbDisable" clearable style="width: 100%;" v-model="zgbForm.approveOpinions"
                placeholder="请输入" type="textarea" :rows="4">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 15px;">
          <el-col :span="24">
            <el-form-item :disabled="zgbDisable" label="审批意见" prop="status">
              <el-radio-group v-model="zgbForm.status">
                <el-radio :label="'6'">接收</el-radio>
                <el-radio :label="'7'">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="审批人" prop="approveUserId">
              <el-select :disabled="zgbDisable" filterable clearable style="width: 100%;" v-model="zgbForm.approveUserId"
                placeholder="请选择">
                <el-option v-for="item in userList" :key="item.value" :label="item.name" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间" prop="approveDate">
              <el-date-picker :disabled="zgbDisable" clearable style="width: 100%;" v-model="zgbForm.approveDate"
                type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="this.ruleForm.status !== '6'" @click="handleClose">取 消</el-button>
      <el-button v-if="saveBtnShow" type="primary" @click="save">
        保存
      </el-button>
    </span>

    <!-- 添加质检单 -->
    <addQualityModal @addTableData="addTableData" @editTableData="editTableData" ref="addQuality"></addQualityModal>
  </el-dialog>
</template>

<script>
import { getDeptList } from "@/api/project/project";
import { getAllUserList } from "@/api/system/user";
import { editQuality, addQuality, getQualityDetail, distributeQuality, approveQuality, checkQuality, reformQuality } from "@/api/project/quality.js";
import addQualityModal from "./addQuality.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getTask } from '@/api/project/task'
export default {
  components: {
    addQualityModal,
    Treeselect
  },
  dicts: ['xmgl_task_qualitytype', 'xmgl_task_qualitymethod'],
  data() {
    return {
      tableData: [],
      queryParams: {},
      ruleForm: {},
      ffForm: {},
      zjForm: {},
      zgbForm: {},
      yjForm: {},
      rules: {
        type: [{ required: true, message: '请选择质检类型', trigger: 'blur' }],
      },
      ffrules: {
        checkMethod: [{ required: true, message: '请选择质检方式', trigger: 'blur' }],
        responsiblePersonId: [{ required: true, message: '请选择质检负责人', trigger: 'blur' }],
        executeDeptId: [{ required: true, message: '请选择质检执行部门', trigger: 'blur' }],
        executorId: [{ required: true, message: '请选择质检执行人', trigger: 'blur' }],
      },
      zjrules: {
        checkTime: [{ required: true, message: '请选择质检完成时间', trigger: 'blur' }],
        checkConclusion: [{ required: true, message: '请选择质检结论', trigger: 'blur' }],
      },
      yjrules: {
        reformOpinions: [{ required: true, message: '请输入整改意见', trigger: 'blur' }],
        reformPromoteDate: [{ required: true, message: '请选择填写人', trigger: 'blur' }],
        reformPromoterId: [{ required: true, message: '请选择填写时间', trigger: 'blur' }],
      },
      zgbrules: {
        approveOpinions: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
        status: [{ required: true, message: '请选择审批意见', trigger: 'blur' }],
        approveUserId: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
        approveDate: [{ required: true, message: '请选选择审批时间', trigger: 'blur' }],
      },
      title: '新增',
      dialogVisible: false,
      userList: [],
      zxrUserList: [], // 执行人
      fzrUserList: [], // 负责人
      deptTreeList: []
    };
  },

  created() {
    this.getAllUserList();
    this.getDeptList();
  },
  computed: {
    // 申请禁用
    sqDisable() {
      if (this.title === '查看') return true;
      return +this.ruleForm?.status > 0
    },
    // 分发禁用
    ffDisable() {
      if (this.title === '查看') return true;
      if (this.$hasPermission(['xmgl:quality:distribute']) && this.ruleForm?.status === '1') return false; // 当前分发步骤
      if (+this.ruleForm.status >= 2) return true; // 说明已经分发完成
    },
    // 质检禁用
    zjDisable() {
      if (this.title === '查看') return true;
      if (this.$hasPermission(['xmgl:quality:check']) && this.ruleForm?.status === '2') return false; // 当前质检步骤
      if (+this.ruleForm.status >= 3) return true; // 说明已经质检完成
    },
    // 整改禁用
    zgDisable() {
      if (this.title === '查看') return true;
      if (this.$hasPermission(['xmgl:quality:reform']) && this.ruleForm?.status === '4') return false; // 当前整改步骤
      if (+this.ruleForm.status >= 5) return true; // 说明已经整改完成
    },
    // 总共办禁用
    zgbDisable() {
      if (this.title === '查看') return true;
      if (this.$hasPermission(['xmgl:quality:approve']) && ['3', '5'].includes(this.ruleForm.status)) return false; // 当前审核步骤
      if (+this.ruleForm.status >= 6) return true; // 说明已经审核完成
    },
    // 分发显示
    ffShowPage() {
      if (this.ruleForm?.status == '1' && this.$hasPermission(['xmgl:quality:distribute'])) {
        return true
      }
      if (+this.ruleForm?.status > 1 && this.$hasPermission(['xmgl:quality:check', 'xmgl:quality:reform', 'xmgl:quality:approve'])) {
        return true;
      }
    },
    // 质检显示
    zjShowPage() {
      if (this.$hasPermission(['xmgl:quality:check']) && this.ruleForm?.status === '2') return true; // 当前质检步骤
      if (+this.ruleForm.status > 2) return true; // 说明已经质检完成
    },
    // 质检整改意见显示
    yjShowPage() {
      if (this.ruleForm.checkConclusion === '3') return false; // 不存在质检整合流程
      if (this.$hasPermission(['xmgl:quality:reform']) && this.ruleForm?.status === '4') return true; // 当前整改步骤
      if (+this.ruleForm.status >= 5) return true; // 说明已经整改完成
    },
    // 总工办审核显示
    zgbShowPage() {
      if (this.$hasPermission(['xmgl:quality:approve']) && ['3', '5'].includes(this.ruleForm.status)) return true; // 总工办审核
      if (this.ruleForm.status === '6') return true // 说明总工办审核完成
    },
    // 保存按钮显示
    saveBtnShow() {
      if (this.title === '查看') {
        return false;
      } else if (this.ruleForm.status === '6') {
        return false; // 全部流程完成
      } else if (this.ruleForm.status === '1' && this.$hasPermission('xmgl:quality:commit')) {
        return false; // 已经提交
      } else if (this.ruleForm.status === '2' && this.$hasPermission('xmgl:quality:distribute')) {
        return false; // 已经分发
      } else if (['3', '4'].includes(this.ruleForm.status) && this.$hasPermission('xmgl:quality:check')) {
        return false; // 已经过了质检
      } else if (this.ruleForm.status === '4' && this.$hasPermission('xmgl:quality:approve')) {
        return false; // 存在质检不通过
      } else if (this.ruleForm.status === '5' && this.$hasPermission('xmgl:quality:reform')) {
        return false; // 完成质检整合
      } else if (['3', '5'].includes(this.ruleForm.status) && !this.$hasPermission('xmgl:quality:approve')) {
        return false // 不是总工办，但是已经完成质检整合或者质检通过
      } else if (['6', '7'].includes(this.ruleForm.status) && this.$hasPermission('xmgl:quality:approve')) {
        return false; // 总工办已经审核
      } else if (!this.ruleForm?.status || (this.$hasPermission(['xmgl:quality:add', 'xmgl:quality:edit']) && ['0', '1'].includes(this.ruleForm.status))) {
        // 添加修改
        return true
      } else {
        return true
      }
    }
  },
  watch: {
    'ffForm.executeDeptId': {
      immediate: true,
      handler(n) {
        // 根据执行部门过滤执行人数据
        let list = JSON.parse(JSON.stringify(this.userList));
        this.zxrUserList = list.filter(item => item.deptId === n);
      }
    }
  },

  methods: {
    getDetailsInfo() {
      getTask(this.$route.query.taskId).then(res => {
        let list = JSON.parse(JSON.stringify(this.userList));
        // 根据任务部门过滤负责人数据
        this.fzrUserList = list.filter(item => item.deptId === res.data.undertakeDeptId);
      })
    },
    // 获取部门树结构
    async getDeptList() {
      const res = await getDeptList();
      this.deptTreeList = res.data
      this.deptTreeList[0].disabled = true;
    },
    // 获取所有用户
    async getAllUserList() {
      const res = await getAllUserList();
      this.userList = res.data;
      this.getDetailsInfo();
    },
    async openModal(id, type) {
      if (id) {
        this.title = '编辑'
        const res = await getQualityDetail(this.$route.query.taskId, id);
        this.ruleForm = JSON.parse(JSON.stringify(res.data));
        this.ffForm = JSON.parse(JSON.stringify(res.data));
        this.zjForm = JSON.parse(JSON.stringify(res.data));
        this.yjForm = JSON.parse(JSON.stringify(res.data));
        this.zgbForm = JSON.parse(JSON.stringify(res.data));
        this.tableData = res.data.content ? JSON.parse(res.data.content) : '';
      } else {
        this.title = '新增';
        this.ruleForm.promoteTime = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
      }
      if (type === 'look') {
        this.title = '查看';
      }
      if (['3', '5'].includes(this.ruleForm.status)) {
        // 总工办添加默认值
        this.zgbForm.approveUserId = this.$store.state.user.id;
        this.zgbForm.approveDate = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
      } else if (this.ruleForm.status === '4') {
        // 整改意见默认值
        this.yjForm.reformPromoterId = this.$store.state.user.id;
        this.yjForm.reformPromoteDate = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
      }
      this.dialogVisible = true;
    },
    // 添加质检内容
    openContentModal() {
      this.$nextTick(() => {
        this.$refs.addQuality.open();
      })
    },
    // 添加表格数据
    addTableData(data) {
      this.tableData.unshift(data);
    },
    // 编辑表格数据
    editTableData(data) {
      let target = this.tableData.find(item => item.guid === data.guid);
      if (target) {
        Object.assign(target, data);
      }
    },
    handleUpdate(row) {
      this.$nextTick(() => {
        row.guid = this.$guid();
        this.$refs.addQuality.open(row);
      })
    },
    // 前端删除
    handleDelete(row) {
      let index = this.tableData.findIndex(item => item.guid === row.guid);
      if (index > -1) {
        this.tableData.splice(index, 1);
      }
    },
    // 关闭弹框
    handleClose() {
      this.resetForm('ruleForm');
      this.resetForm('ffForm');
      this.resetForm('zjForm');
      this.resetForm('yjForm');
      this.resetForm('zgbForm');
      this.ruleForm = this.$options.data().ruleForm;
      this.ffForm = this.$options.data().ffForm;
      this.zjForm = this.$options.data().zjForm;
      this.yjForm = this.$options.data().yjForm;
      this.zgbForm = this.$options.data().zgbForm;
      this.tableData = [];
      this.dialogVisible = false;
    },
    // 保存按钮
    save() {
      if (this.$hasPermission(['xmgl:quality:add', 'xmgl:quality:edit']) && (!this.ruleForm.status || this.ruleForm.status == '0')) {
        this.$refs["ruleForm"].validate(valid => {
          if (valid) {
            if (!this.tableData.length) return this.$modal.msgError("请填写质检内容！");
            this.ruleForm.contentValue = this.tableData;
            this.ruleForm.taskId = this.$route.query.taskId;
            if (this.ruleForm.id != undefined) {
              editQuality(this.ruleForm.taskId, this.ruleForm).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.handleClose();
                this.$emit('getList');
              });
            } else {
              addQuality(this.ruleForm.taskId, this.ruleForm).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.handleClose();
                this.$emit('getList');
              });
            }
          }
        });
      }

      // 分发权限
      if (this.$hasPermission(['xmgl:quality:distribute']) && this.ruleForm.status == '1') {
        this.$refs["ffForm"].validate(async valid => {
          if (!valid) return;
          this.ffForm.responsiblePerson = this.$refs.zjfzrSelect.selected.label;
          const res = await distributeQuality(this.$route.query.taskId, this.ffForm);
          if (res.code = 200) {
            this.$modal.msgSuccess("操作成功");
            this.handleClose();
            this.$emit('getList');
          }
        })
      }

      // 质检权限
      if (this.$hasPermission(['xmgl:quality:check']) && this.ruleForm.status == '2') {
        this.$refs["zjForm"].validate(async valid => {
          if (!valid) return;
          const res = await checkQuality(this.$route.query.taskId, this.zjForm);
          if (res.code = 200) {
            this.$modal.msgSuccess("操作成功");
            this.handleClose();
            this.$emit('getList');
          }
        })
      }

      // 整改权限
      if (this.$hasPermission(['xmgl:quality:reform']) && this.ruleForm.status == '4') {
        this.$refs["yjForm"].validate(async valid => {
          if (!valid) return;
          const res = await reformQuality(this.$route.query.taskId, this.yjForm);
          if (res.code = 200) {
            this.$modal.msgSuccess("操作成功");
            this.handleClose();
            this.$emit('getList');
          }
        })
      }

      // 总工办权限
      if (this.$hasPermission(['xmgl:quality:approve']) && ['3', '5'].includes(this.ruleForm.status)) {
        this.$refs["zgbForm"].validate(async valid => {
          if (!valid) return;
          const res = await approveQuality(this.ruleForm.taskId, this.zgbForm);
          if (res.code = 200) {
            this.$modal.msgSuccess("操作成功");
            this.handleClose();
            this.$emit('getList');
          }
        })
      }
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children
      };
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  width: 100%;
  max-height: 780px;
  overflow-y: auto;
  overflow-x: hidden;

  .el-divider__text {
    font-size: 20px;
  }
}
</style>
